package com.goldsign.pay.common.util;

import com.goldsign.pay.common.log.SysLog;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.HashMap;
import java.util.Map;

public class SpringUtil implements ApplicationContextAware {
	
	/**默认上下文对象(由applicationContext-*.xml定义)*/
	private static ApplicationContext applicationContext;
	
	/**工厂集,以配置文件名作为扩展名存储,如applicationContext-*,applicationContext-service等 */
	private static Map<String,ApplicationContext> applicationContexts = new HashMap<String,ApplicationContext>();

	/**得到默认bean工厂*/
	public static ApplicationContext getApplicationContext() {
		return getApplicationContext(null);
	}
	/**获取指定了上下文文件的Bean工厂*/
	public static ApplicationContext getApplicationContext(String contextName) {
		if(contextName == null){
			if(applicationContext != null){
				return applicationContext;
			}
			contextName = "applicationContext-*.xml";
		}
		ApplicationContext context = applicationContexts.get(contextName);
		if(context != null){
			SysLog.info("Getted application contexts,classpath:" + contextName);
			return context;
		}
		SysLog.info("doing application context config,classpath:" + contextName);
        try {
        	context = new ClassPathXmlApplicationContext(contextName);
        	applicationContexts.put(contextName, context);
        } catch (Exception e) {
			SysLog.error(e.getMessage());
        	return null;
        }
		SysLog.info("config application context finish");
		return context;
	}
	public static Object getBean(String beanId){
		return getApplicationContext().getBean(beanId);
	}
	/**
	 * 获取Bean
	 * @param beanId Spring配置文件的bean id
	 * @param contextName Spring配置文件名
	 * @return
	 */
	public static Object getBean(String beanId,String contextName){
		return getApplicationContext(contextName).getBean(beanId);
	}

	/**实现ApplicationContextAware的方法,将注入的上下文对象存入Map,key=SpringAutoContext*/
	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		SysLog.info("Spring初始化,设置上下文对象到SpringUtil.");
		SpringUtil.applicationContext = context;
		SpringUtil.applicationContexts.put("SpringAutoContext", context);
	}
	public static Map<String, ApplicationContext> getApplicationContexts() {
		return applicationContexts;
	}
	
	

}
